package com.yangtu.nearbyshop.wx.web;

import com.yangtu.nearbyshop.core.util.GeoUtils;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.*;
import com.yangtu.nearbyshop.db.util.CouponUserConstant;
import com.yangtu.nearbyshop.db.util.OrderUtil;
import com.yangtu.nearbyshop.db.vo.OrderInfoVo;
import com.yangtu.nearbyshop.wx.util.WxResponseCode;
import com.yangtu.nearbyshop.wx.annotation.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.yangtu.nearbyshop.core.util.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 用户购物车服务
 */
@RestController
@RequestMapping("/wx/cart")
@Validated
public class WxCartController {
    private final Log logger = LogFactory.getLog(WxCartController.class);

    @Autowired
    private NearbyshopCartService cartService;
    @Autowired
    private NearbyshopGoodsService goodsService;
    @Autowired
    private NearbyshopOrderGoodsService orderGoodsService;
    @Autowired
    private NearbyshopGoodsProductService productService;
    @Autowired
    private NearbyshopAddressService addressService;
    @Autowired
    private NearbyshopGrouponRulesService grouponRulesService;
    @Autowired
    private NearbyshopCouponService couponService;
    @Autowired
    private NearbyshopCouponUserService couponUserService;
    @Autowired
    private CouponVerifyService couponVerifyService;
    @Autowired
    private NearbyshopMercService mercService;
    @Autowired
    private NearbyshopAdminService adminService;
    /**
     * 用户购物车信息
     *
     * @param userId 用户ID
     * @return 用户购物车信息
     */
    @GetMapping("index")
    public Object index(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        List<NearbyshopCart> cartList = cartService.queryByUid(userId);
        Integer goodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0.00);
        Integer checkedGoodsCount = 0;
        BigDecimal checkedGoodsAmount = new BigDecimal(0.00);
        for (NearbyshopCart cart : cartList) {
            goodsCount += cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            if (cart.getChecked()) {
                checkedGoodsCount += cart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("goodsAmount", goodsAmount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount);

        Map<String, Object> result = new HashMap<>();
        result.put("cartList", cartList);
        result.put("cartTotal", cartTotal);

        return ResponseUtil.ok(result);
    }

    /**
     * 加入商品到购物车
     * <p>
     * 如果已经存在购物车货品，则增加数量；
     * 否则添加新的购物车货品项。
     *
     * @param userId 用户ID
     * @param cart   购物车商品信息， { goodsId: xxx, productId: xxx, number: xxx }
     * @return 加入购物车操作结果
     */
    @PostMapping("add")
    public Object add(@LoginUser Integer userId, @RequestBody NearbyshopCart cart) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (cart == null) {
            return ResponseUtil.badArgument();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
            return ResponseUtil.badArgument();
        }

        //判断商品是否可以购买
        NearbyshopGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE, "商品已下架");
        }

        //判断用户是否已超出限购数量
        //还可以购买的数量
        if(goods.getSaleLimit()>=0){
           /* Integer count = goods.getSaleLimit() - orderGoodsService.countByGoodsId(userId,goodsId);
            if (number > count) {*/
                return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE,
                        "禁止加购物车");
            //}
        }

        NearbyshopGoodsProduct product = productService.findById(productId);
        //判断购物车中是否存在此规格商品
        NearbyshopCart existCart = cartService.queryExist(goodsId, productId, userId);
        if (existCart == null) {
            //取得规格的信息,判断规格库存
            if (product == null || number > product.getNumber()) {
                return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
            }

            cart.setId(null);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName((goods.getName()));
            cart.setPicUrl(goods.getPicUrl());
            cart.setPrice(product.getPrice());
            cart.setMercProfit(product.getMercProfit());
            cart.setSpecifications(product.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        } else {
            //取得规格的信息,判断规格库存
            int num = existCart.getNumber() + number;
            if (num > product.getNumber()) {
                return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
            }
            existCart.setNumber((short) num);
            if (cartService.updateById(existCart) == 0) {
                return ResponseUtil.updatedDataFailed();
            }
        }

        return goodscount(userId);
    }

    /**
     * 从购物车删除一个商品
     * <p>
     * 如果已经存在购物车货品，则减少数量；
     * 否则删除购物车货品项。
     *
     * @param userId 用户ID
     * @param cart   购物车商品信息， { goodsId: xxx, productId: xxx, number: xxx }
     * @return 加入购物车操作结果
     */
    @PostMapping("remove")
    public Object remove(@LoginUser Integer userId, @RequestBody NearbyshopCart cart) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (cart == null) {
            return ResponseUtil.badArgument();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
            return ResponseUtil.badArgument();
        }

        NearbyshopGoodsProduct product = productService.findById(productId);
        //判断购物车中是否存在此规格商品
        NearbyshopCart existCart = cartService.queryExist(goodsId, productId, userId);

        //取得规格的信息,判断规格库存
        int num = existCart.getNumber() - number;
        //删除商品数目为0时，删除该商品
        if (num == 0) {
            List<Integer> productIds = new ArrayList<>();
            productIds.add(productId);
            cartService.delete(productIds, userId);
            return goodscount(userId);
        }
        existCart.setNumber((short) num);
        if (cartService.updateById(existCart) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return goodscount(userId);
    }

    /**
     * 立即购买
     * <p>
     * 和add方法的区别在于：
     * 1. 如果购物车内已经存在购物车货品，前者的逻辑是数量添加，这里的逻辑是数量覆盖
     * 2. 添加成功以后，前者的逻辑是返回当前购物车商品数量，这里的逻辑是返回对应购物车项的ID
     *
     * @param userId 用户ID
     * @param cart   购物车商品信息， { goodsId: xxx, productId: xxx, number: xxx }
     * @return 立即购买操作结果
     */
    @PostMapping("fastadd")
    public Object fastadd(@LoginUser Integer userId, @RequestBody NearbyshopCart cart) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (cart == null) {
            return ResponseUtil.badArgument();
        }

        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        if (!ObjectUtils.allNotNull(productId, number, goodsId)) {
            return ResponseUtil.badArgument();
        }

        //判断商品是否可以购买
        NearbyshopGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE,
                    "商品已下架");
        }

        //判断用户是否已超出限购数量
        //还可以购买的数量
        if(goods.getSaleLimit()>=0){
            Integer count = goods.getSaleLimit() - orderGoodsService.countByGoodsId(userId,goodsId);
            if (number > count) {
                return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE,
                        "限购"+goods.getSaleLimit()+"次哦！");
            }
        }

        NearbyshopGoodsProduct product = productService.findById(productId);
        //判断购物车中是否存在此规格商品
        NearbyshopCart existCart = cartService.queryExist(goodsId, productId, userId);
        if (existCart == null) {
            //取得规格的信息,判断规格库存
            if (product == null || number > product.getNumber()) {
                return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
            }

            cart.setId(null);
            cart.setGoodsSn(goods.getGoodsSn());
            cart.setGoodsName((goods.getName()));
            cart.setPicUrl(goods.getPicUrl());
            cart.setPrice(product.getPrice());
            cart.setMercProfit(product.getMercProfit());
            cart.setSpecifications(product.getSpecifications());
            cart.setUserId(userId);
            cart.setChecked(true);
            cartService.add(cart);
        } else {
            //取得规格的信息,判断规格库存
            int num = number;
            if (num > product.getNumber()) {
                return ResponseUtil.fail(WxResponseCode.GOODS_NO_STOCK, "库存不足");
            }
            existCart.setNumber((short) num);
            if (cartService.updateById(existCart) == 0) {
                return ResponseUtil.updatedDataFailed();
            }
        }

        return ResponseUtil.ok(existCart != null ? existCart.getId() : cart.getId());
    }

    /**
     * 修改购物车商品货品数量
     *
     * @param userId 用户ID
     * @param cart   购物车商品信息， { id: xxx, goodsId: xxx, productId: xxx, number: xxx }
     * @return 修改结果
     */
    @PostMapping("update")
    public Object update(@LoginUser Integer userId, @RequestBody NearbyshopCart cart) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (cart == null) {
            return ResponseUtil.badArgument();
        }
        Integer productId = cart.getProductId();
        Integer number = cart.getNumber().intValue();
        Integer goodsId = cart.getGoodsId();
        Integer id = cart.getId();
        if (!ObjectUtils.allNotNull(id, productId, number, goodsId)) {
            return ResponseUtil.badArgument();
        }

        //判断是否存在该订单
        // 如果不存在，直接返回错误
        NearbyshopCart existCart = cartService.findById(id);
        if (existCart == null) {
            return ResponseUtil.badArgumentValue();
        }

        // 判断goodsId和productId是否与当前cart里的值一致
        if (!existCart.getGoodsId().equals(goodsId)) {
            return ResponseUtil.badArgumentValue();
        }
        if (!existCart.getProductId().equals(productId)) {
            return ResponseUtil.badArgumentValue();
        }

        //判断商品是否可以购买
        NearbyshopGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE, "商品已下架");
        }

        //判断用户是否已超出限购数量
        //还可以购买的数量
        if(goods.getSaleLimit()>=0){
            Integer count = goods.getSaleLimit() - orderGoodsService.countByGoodsId(userId,goodsId);
            if (number > count) {
                return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE,
                        "限购"+goods.getSaleLimit()+"次哦！");
            }
        }

        //取得规格的信息,判断规格库存
        NearbyshopGoodsProduct product = productService.findById(productId);
        if (product == null || product.getNumber() < number) {
            return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE, "库存不足");
        }

        existCart.setNumber(number.shortValue());
        if (cartService.updateById(existCart) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok();
    }

    /**
     * 购物车商品货品勾选状态
     * <p>
     * 如果原来没有勾选，则设置勾选状态；如果商品已经勾选，则设置非勾选状态。
     *
     * @param userId 用户ID
     * @param body   购物车商品信息， { productIds: xxx, isChecked: 1/0 }
     * @return 购物车信息
     */
    @PostMapping("checked")
    public Object checked(@LoginUser Integer userId, @RequestBody String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (body == null) {
            return ResponseUtil.badArgument();
        }

        List<Integer> productIds = JacksonUtil.parseIntegerList(body, "productIds");
        if (productIds == null) {
            return ResponseUtil.badArgument();
        }

        Integer checkValue = JacksonUtil.parseInteger(body, "isChecked");
        if (checkValue == null) {
            return ResponseUtil.badArgument();
        }
        Boolean isChecked = (checkValue == 1);

        cartService.updateCheck(userId, productIds, isChecked);
        return index(userId);
    }

    /**
     * 购物车商品删除
     *
     * @param userId 用户ID
     * @param body   购物车商品信息， { productIds: xxx }
     * @return 购物车信息
     * 成功则
     * {
     * errno: 0,
     * errmsg: '成功',
     * data: xxx
     * }
     * 失败则 { errno: XXX, errmsg: XXX }
     */
    @PostMapping("delete")
    public Object delete(@LoginUser Integer userId, @RequestBody String body) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (body == null) {
            return ResponseUtil.badArgument();
        }

        List<Integer> productIds = JacksonUtil.parseIntegerList(body, "productIds");

        if (productIds == null || productIds.size() == 0) {
            return ResponseUtil.badArgument();
        }

        cartService.delete(productIds, userId);
        return index(userId);
    }

    /**
     * 购物车商品货品数量
     * <p>
     * 如果用户没有登录，则返回空数据。
     *
     * @param userId 用户ID
     * @return 购物车商品货品数量
     */
    @GetMapping("goodscount")
    public Object goodscount(@LoginUser Integer userId) {
        if (userId == null) {
            return ResponseUtil.ok(0);
        }

        int goodsCount = 0;
        List<NearbyshopCart> cartList = cartService.queryByUid(userId);
        for (NearbyshopCart cart : cartList) {
            goodsCount += cart.getNumber();
        }

        return ResponseUtil.ok(goodsCount);
    }

    /**
     * 购物车下单
     *
     * @param userId    用户ID
     * @param cartId    购物车商品ID：
     *                  如果购物车商品ID是空，则下单当前用户所有购物车商品；
     *                  如果购物车商品ID非空，则只下单当前购物车商品。
     * @param couponId  优惠券ID：
     *                  如果优惠券ID是空，则自动选择合适的优惠券。
     * @return 购物车操作结果
     */
    @GetMapping("checkout")
    public Object checkout(@LoginUser Integer userId, Integer cartId,
                           Integer couponId, Integer grouponRulesId,
                           String longitude,String latitude) {

        /*
        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        // 团购优惠
        BigDecimal grouponPrice = new BigDecimal(0.00);
        NearbyshopGrouponRules grouponRules = grouponRulesService.queryById(grouponRulesId);
        if (grouponRules != null) {
            grouponPrice = grouponRules.getDiscount();
        }

        // 商品价格
        List<NearbyshopCart> checkedGoodsList = null;
        if (cartId == null || cartId.equals(0)) {
            checkedGoodsList = cartService.queryByUidAndChecked(userId);
        } else {
            NearbyshopCart cart = cartService.findById(cartId);
            if (cart == null) {
                return ResponseUtil.badArgumentValue();
            }
            checkedGoodsList = new ArrayList<>(1);
            checkedGoodsList.add(cart);
        }
        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        for (NearbyshopCart cart : checkedGoodsList) {
            //判断用户是否已超出限购数量
            //还可以购买的数量
            NearbyshopGoods goods = goodsService.findById(cart.getGoodsId());
            if(goods.getSaleLimit()>=0){
                Integer count = goods.getSaleLimit() - orderGoodsService.countByGoodsId(userId,goods.getId());
                if (cart.getNumber() > count) {
                    return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE,
                            "有限购品！");
                }
            }

            //  只有当团购规格商品ID符合才进行团购优惠
            if (grouponRules != null && grouponRules.getGoodsId().equals(cart.getGoodsId())) {
                checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().subtract(grouponPrice).multiply(new BigDecimal(cart.getNumber())));
            } else {
                checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }


        }
*/
        // 计算优惠券可用情况
        BigDecimal tmpCouponPrice = new BigDecimal(0.00);
        Integer tmpCouponId = 0;
        int tmpCouponLength = 0;
        List<NearbyshopCouponUser> couponUserList = couponUserService.queryAll(userId);
        /*
        for(NearbyshopCouponUser couponUser : couponUserList){
            NearbyshopCoupon coupon = couponVerifyService.checkCoupon(userId, couponUser.getCouponId(), checkedGoodsPrice);
            if(coupon == null){
                continue;
            }

            tmpCouponLength++;
            if(tmpCouponPrice.compareTo(coupon.getDiscount()) == -1){
                tmpCouponPrice = coupon.getDiscount();
                tmpCouponId = coupon.getId();
            }
        }
        // 获取优惠券减免金额，优惠券可用数量
        int availableCouponLength = tmpCouponLength;


        BigDecimal couponPrice = new BigDecimal(0);
        // 这里存在三种情况
        // 1. 用户不想使用优惠券，则不处理
        // 2. 用户想自动使用优惠券，则选择合适优惠券
        // 3. 用户已选择优惠券，则测试优惠券是否合适
        if (couponId == null || couponId.equals(-1)){
            couponId = -1;
        }
        else if (couponId.equals(0)) {
            couponPrice = tmpCouponPrice;
            couponId = tmpCouponId;
        }
        else {
            NearbyshopCoupon coupon = couponVerifyService.checkCoupon(userId, couponId, checkedGoodsPrice);
            // 用户选择的优惠券有问题
            if(coupon == null){
                return ResponseUtil.badArgumentValue();
            }
            couponPrice = coupon.getDiscount();
        }

        // 根据订单商品总价计算运费，满88则免运费，否则8元；
        BigDecimal freightPrice = new BigDecimal(0.00);
//        if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
//            freightPrice = SystemConfig.getFreight();
//        }

        // 可以使用的其他钱，例如用户积分
        BigDecimal integralPrice = new BigDecimal(0.00);

        // 订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice);
        BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);




        Map<String, Object> data = new HashMap<>();
        data.put("grouponRulesId", grouponRulesId);
        data.put("grouponPrice", grouponPrice);
        data.put("couponId", couponId);
        data.put("availableCouponLength", availableCouponLength);
        data.put("goodsTotalPrice", checkedGoodsPrice);
        data.put("freightPrice", freightPrice);
        data.put("couponPrice", couponPrice);
        data.put("orderTotalPrice", orderTotalPrice);
        data.put("actualPrice", actualPrice);
        data.put("checkedGoodsList", checkedGoodsList);
        return ResponseUtil.ok(data);

         */

        if (userId == null) {
            return ResponseUtil.unlogin();
        }

        if(StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude) ){
            return ResponseUtil.fail("经纬度不能为空");
        }

        //String mercNo = user.getMercNo();

        //如果是团购项目,验证活动是否有效
        if (grouponRulesId != null && grouponRulesId > 0) {
            NearbyshopGrouponRules rules = grouponRulesService.queryById(grouponRulesId);
            //找不到记录
            if (rules == null) {
                return ResponseUtil.badArgument();
            }
            //团购活动已经过期
            if (grouponRulesService.isExpired(rules)) {
                return ResponseUtil.fail(WxResponseCode.GROUPON_EXPIRED, "团购活动已过期!");
            }
        }

        if (cartId == null || couponId == null ) {
            return ResponseUtil.badArgument();
        }

        // 收货地址
//        NearbyshopAddress checkedAddress = addressService.findById(addressId);
//        if (checkedAddress == null) {
//            return ResponseUtil.badArgument();
//        }

        // 团购优惠
        BigDecimal grouponPrice = new BigDecimal(0.00);
        NearbyshopGrouponRules grouponRules = grouponRulesService.queryById(grouponRulesId);
        if (grouponRules != null) {
            grouponPrice = grouponRules.getDiscount();
        }

        // 货品价格
        List<NearbyshopCart> checkedGoodsList = null;
        if (cartId.equals(0)) {
            checkedGoodsList = cartService.queryByUidAndChecked(userId);
        } else {
            NearbyshopCart cart = cartService.findById(cartId);
            checkedGoodsList = new ArrayList<>(1);
            checkedGoodsList.add(cart);
        }
        if (checkedGoodsList.size() == 0) {
            return ResponseUtil.badArgumentValue();
        }
//        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        Map<Integer, OrderInfoVo> subOrders = new HashMap<>();
        for (NearbyshopCart checkGoods : checkedGoodsList) {
            OrderInfoVo orderInfoVo = null;
            //判断用户是否已超出限购数量
            //还可以购买的数量
            NearbyshopGoods goods = goodsService.findById(checkGoods.getGoodsId());
            if(goods.getSaleLimit()>=0){
                Integer count = goods.getSaleLimit() - orderGoodsService.countByGoodsId(userId,goods.getId());
                if (checkGoods.getNumber() > count) {
                    return ResponseUtil.fail(WxResponseCode.GOODS_UNSHELVE,
                            "有限购品！");
                }
            }

            if(!subOrders.containsKey(goods.getBrandId())){
                orderInfoVo = new OrderInfoVo();
                orderInfoVo.setAdminId(goods.getBrandId());
                orderInfoVo.setCheckedGoodsPrice(new BigDecimal(0.00));
                orderInfoVo.setCouponPrice(new BigDecimal(0.00));
                orderInfoVo.setGrouponPrice(new BigDecimal(0.00));
                subOrders.put(goods.getBrandId(),orderInfoVo);
            }else {
                orderInfoVo = subOrders.get(goods.getBrandId());
            }

            //  只有当团购规格商品ID符合才进行团购优惠
            if (grouponRules != null && grouponRules.getGoodsId().equals(checkGoods.getGoodsId())) {
                orderInfoVo.setCheckedGoodsPrice(orderInfoVo.getCheckedGoodsPrice()
                        .add(checkGoods.getPrice().subtract(grouponPrice)
                                .multiply(new BigDecimal(checkGoods.getNumber()))));
                orderInfoVo.setGrouponPrice(grouponPrice);
            } else {
                orderInfoVo.setCheckedGoodsPrice(orderInfoVo.getCheckedGoodsPrice()
                        .add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber()))));
            }

        }
        //找到费用最高的
        Iterator iter = subOrders.keySet().iterator();
        OrderInfoVo orderInfoVo = null;
        BigDecimal minPrice = new BigDecimal(0.00);
        while (iter.hasNext()) {
            OrderInfoVo infoVo = subOrders.get((Integer)iter.next());
            if(infoVo.getCheckedGoodsPrice().compareTo(minPrice) == 1){
                orderInfoVo = infoVo;
            }
        }
        // 获取可用的优惠券信息
        // 使用优惠券减免的金额
        //BigDecimal couponPrice = new BigDecimal(0.00);
        // 如果couponId=0则没有优惠券，couponId=-1则不使用优惠券
        if (couponId != 0 && couponId != -1) {
            NearbyshopCoupon coupon = couponVerifyService.checkCoupon(userId, couponId, orderInfoVo.getCheckedGoodsPrice());
            if (coupon == null) {
                return ResponseUtil.badArgumentValue();
            }
            orderInfoVo.setCouponPrice(coupon.getDiscount());
        }

        // 根据订单商品总价计算运费，满足条件（例如88元）则免运费，否则需要支付运费（例如8元）；
        BigDecimal freightPrice = new BigDecimal(0.00);
//        if (checkedGoodsPrice.compareTo(SystemConfig.getFreightLimit()) < 0) {
//            freightPrice = SystemConfig.getFreight();
//        }

        // 可以使用的其他钱，例如用户积分
        BigDecimal integralPrice = new BigDecimal(0.00);

        // 订单费用
        //BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice);
        // 最终支付费用
        //BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);

        //Integer orderId = null;
        Integer couponOrderId = null;
        Integer groupOrderId = null;
        NearbyshopOrder order = null;
        // 订单
        Iterator iter2 = subOrders.keySet().iterator();
        String orderIds = "";
        BigDecimal totalActPrice = new BigDecimal(0.00);
        BigDecimal totalGoodsPrice = new BigDecimal(0.00);
        BigDecimal totalFreightPrice = new BigDecimal(0.00);
        BigDecimal totalCouponPrice = new BigDecimal(0.00);
        BigDecimal totalIntegralPrice = new BigDecimal(0.00);
        BigDecimal totalOrderPrice = new BigDecimal(0.00);
        BigDecimal totalGrouponPrice = new BigDecimal(0.00);
        BigDecimal totalYouhuiPrice = new BigDecimal(0.00);
        BigDecimal totalBuchaPrice = new BigDecimal(0.00);
//        String comOrderSn = orderService.generateOrderSn(userId);
        while (iter2.hasNext()){
            OrderInfoVo infoVo = subOrders.get((Integer)iter2.next());
            order = new NearbyshopOrder();
            order.setUserId(userId);
            order.setAdminId(infoVo.getAdminId());
            order.setCorgOrderSn("test");

            order.setOrderStatus(OrderUtil.STATUS_CREATE);
//        order.setConsignee(checkedAddress.getName());
//        order.setMobile(checkedAddress.getMobile());

//        String detailedAddress = detailedAddress(checkedAddress);
//            String detailedAddress ="";

            order.setGoodsPrice(infoVo.getCheckedGoodsPrice());
            order.setFreightPrice(freightPrice);
            order.setCouponPrice(infoVo.getCouponPrice());
            order.setIntegralPrice(integralPrice);
            BigDecimal orderTotalPrice = infoVo.getCheckedGoodsPrice().add(freightPrice).subtract(infoVo.getCouponPrice());
            order.setOrderPrice(orderTotalPrice);
            BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);
            order.setActualPrice(actualPrice);

            order.setDeleted(true);
            // 有团购活动
            if (grouponRules != null) {
                order.setGrouponPrice(infoVo.getGrouponPrice());    //  团购价格
            } else {
                order.setGrouponPrice(new BigDecimal(0.00));    //  团购价格
            }
            totalGrouponPrice = totalGrouponPrice.add(order.getGrouponPrice());
            // 添加订单表项
            //orderService.add(order);
            if(infoVo.getCouponPrice().compareTo(new BigDecimal(0.00))  != 0 ){
                couponOrderId = order.getId();
            }

            if(infoVo.getGrouponPrice().compareTo(new BigDecimal(0.00))  != 0 ){
                groupOrderId = order.getId();
            }

            // 添加订单商品表项
            BigDecimal maxYunfei = new BigDecimal(0.00);
            BigDecimal zongYunfei = new BigDecimal(0.00);
            int totalNum = 0;
            for (NearbyshopCart cartGoods : checkedGoodsList) {
                NearbyshopGoods goods = goodsService.findById(cartGoods.getGoodsId());
                if(goods.getBrandId().equals(infoVo.getAdminId())){
                    // 订单商品
                    NearbyshopOrderGoods orderGoods = new NearbyshopOrderGoods();
                    orderGoods.setOrderId(order.getId());
                    orderGoods.setGoodsId(cartGoods.getGoodsId());
                    orderGoods.setGoodsSn(cartGoods.getGoodsSn());
                    orderGoods.setProductId(cartGoods.getProductId());

                    NearbyshopGoodsProduct goodsProduct = productService.findById(cartGoods.getProductId());
                    if(goodsProduct.getFreightPrice().compareTo(maxYunfei)  > 0 ){
                        maxYunfei = goodsProduct.getFreightPrice();
                    }

                    orderGoods.setGoodsName(cartGoods.getGoodsName());
                    orderGoods.setPicUrl(cartGoods.getPicUrl());
                    orderGoods.setPrice(cartGoods.getPrice());
                    orderGoods.setNumber(cartGoods.getNumber());
                    orderGoods.setSpecifications(cartGoods.getSpecifications());
                    orderGoods.setAddTime(LocalDateTime.now());
                    orderGoods.setMercProfit(cartGoods.getMercProfit());
                    //orderGoods.setMercNo(mercNo);
                    //orderGoodsService.add(orderGoods);
                    totalNum=totalNum+cartGoods.getNumber();
                    zongYunfei = zongYunfei.add(goodsProduct.getFreightPrice().multiply(new BigDecimal(cartGoods.getNumber())));
                }
            }

            NearbyshopAdmin orderAdmin = adminService.findById(order.getAdminId());

            //BigDecimal zongJian = maxYunfei.multiply(new BigDecimal(totalNum-1));
            BigDecimal youhui = zongYunfei.subtract(maxYunfei).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().negate();
            logger.info("youhui=" + youhui);
            BigDecimal bucha = GeoUtils.calcBucha(Double.valueOf(latitude),Double.valueOf(longitude),
                    Double.valueOf(orderAdmin.getLatitude()),Double.valueOf(orderAdmin.getLongitude()));
            logger.info("bucha=" + bucha);
            NearbyshopOrder orderUpdate = new NearbyshopOrder();
            orderUpdate.setId(order.getId());
            orderUpdate.setYouhuiPrice(youhui);
            orderUpdate.setBuchaPrice(bucha);
            //重新计算运费
            orderUpdate.setFreightPrice(bucha.add(youhui).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros());
            //重新设置实际支付金额
            orderUpdate.setActualPrice(order.getActualPrice().add(orderUpdate.getFreightPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros());
//            orderService.updateWithOptimisticLocker(orderUpdate);

            totalFreightPrice = totalFreightPrice.add(orderUpdate.getFreightPrice());
            totalYouhuiPrice = totalYouhuiPrice.add(youhui);
            totalBuchaPrice = totalBuchaPrice.add(bucha);
            totalActPrice = totalActPrice.add(orderUpdate.getActualPrice());
            totalCouponPrice = totalCouponPrice.add(order.getCouponPrice());

            totalGoodsPrice = totalGoodsPrice.add(order.getGoodsPrice());
            totalIntegralPrice = totalIntegralPrice.add(order.getIntegralPrice());
            totalOrderPrice = totalOrderPrice.add(order.getOrderPrice());
            orderIds += order.getId()+",";
        }

        // 删除购物车里面的商品信息
 //       cartService.clearGoods(userId);

        // 商品货品数量减少
 /*         for (NearbyshopCart checkGoods : checkedGoodsList) {
            Integer productId = checkGoods.getProductId();
            NearbyshopGoodsProduct product = productService.findById(productId);

            Integer remainNumber = product.getNumber() - checkGoods.getNumber();
            if (remainNumber < 0) {
                throw new RuntimeException("下单的商品货品数量大于库存量");
            }
            if (productService.reduceStock(productId, checkGoods.getNumber()) == 0) {
                throw new RuntimeException("商品货品库存减少失败");
            }

          NearbyshopGoods goods = goodsService.findById(checkGoods.getGoodsId());
            if(goods.getSaleLimit()!=-1 && goods.getSaleDone() >= goods.getSaleLimit()){
                throw new RuntimeException("商品限购，数量不足");
            }

            //如果是限购商品，修改可购买商品数量
            if (goodsService.reduceLimit(productId, checkGoods.getNumber()) == 0) {
                throw new RuntimeException("商品可购买数量修改失败");
            }
        }*/

        // 如果使用了优惠券，设置优惠券使用状态
//        if (couponId != 0 && couponId != -1) {
//            NearbyshopCouponUser couponUser = couponUserService.queryOne(userId, couponId);
//            couponUser.setStatus(CouponUserConstant.STATUS_USED);
//            couponUser.setUsedTime(LocalDateTime.now());
//            couponUser.setOrderId(couponOrderId);
//            couponUserService.update(couponUser);
//        }

        //如果是团购项目，添加团购信息
        if (grouponRulesId != null && grouponRulesId > 0) {
            NearbyshopGroupon groupon = new NearbyshopGroupon();
            groupon.setOrderId(groupOrderId);
            groupon.setPayed(false);
            groupon.setUserId(userId);
            groupon.setRulesId(grouponRulesId);

//            //参与者
//            if (grouponLinkId != null && grouponLinkId > 0) {
//                //参与的团购记录
//                NearbyshopGroupon baseGroupon = grouponService.queryById(grouponLinkId);
//                groupon.setCreatorUserId(baseGroupon.getCreatorUserId());
//                groupon.setGrouponId(grouponLinkId);
//                groupon.setShareUrl(baseGroupon.getShareUrl());
//            } else {
//                groupon.setCreatorUserId(userId);
//                groupon.setGrouponId(0);
//            }
//
//            grouponService.createGroupon(groupon);
        }
        orderIds = (orderIds.substring(0,orderIds.length()-1));
        NearbyshopOrder comOrder = new NearbyshopOrder();
        comOrder.setUserId(userId);
        comOrder.setCorgOrderSn(orderIds);
//        comOrder.setMercNo(mercNo);
//        comOrder.setOrderSn(comOrderSn);
        comOrder.setOrderStatus(OrderUtil.STATUS_CREATE);
//        comOrder.setConsignee(consignee);
//        comOrder.setMobile(mobile);
//        comOrder.setMessage(message);
//        comOrder.setAddress(detailedAddress);
        comOrder.setGoodsPrice(totalGoodsPrice);
        comOrder.setFreightPrice(totalFreightPrice);
        comOrder.setCouponPrice(totalCouponPrice);
        comOrder.setIntegralPrice(totalIntegralPrice);
        //BigDecimal orderTotalPrice = infoVo.getCheckedGoodsPrice().add(freightPrice).subtract(infoVo.getCouponPrice());
        comOrder.setOrderPrice(totalOrderPrice);
        //BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);
        comOrder.setActualPrice(totalActPrice);
        comOrder.setGrouponPrice(totalGrouponPrice);
        comOrder.setYouhuiPrice(totalYouhuiPrice);
        comOrder.setBuchaPrice(totalBuchaPrice);
/*        // 有团购活动
        if (grouponRules != null) {
            comOrder.setGrouponPrice(infoVo.getGrouponPrice());    //  团购价格
        } else {
            comOrder.setGrouponPrice(new BigDecimal(0.00));    //  团购价格
        }*/

        // 添加订单表项
        //orderService.add(comOrder);


/*        Map<String, Object> data = new HashMap<>();
//        data.put("orderId", (orderIds.substring(0,orderIds.length()-1)));
        data.put("orderId", comOrder.getId());*/

        Map<String, Object> data = new HashMap<>();
        data.put("grouponRulesId", grouponRulesId);
        data.put("grouponPrice", grouponPrice);
        data.put("couponId", couponId);
        data.put("availableCouponLength", couponUserList.size());
        data.put("goodsTotalPrice", comOrder.getGoodsPrice());
        data.put("freightPrice", comOrder.getFreightPrice());
        data.put("buchaPrice", comOrder.getBuchaPrice());
        data.put("youhuiPrice", comOrder.getYouhuiPrice());
        data.put("couponPrice", comOrder.getCouponPrice());
        data.put("orderTotalPrice", comOrder.getOrderPrice());
        data.put("actualPrice", comOrder.getActualPrice());
        data.put("checkedGoodsList", checkedGoodsList);
        return ResponseUtil.ok(data);

    }
}
